"""API路由模块"""
from fastapi import FastAPI, HTTPException
from typing import List, Optional
import json
from .config import API_CONFIG, logger
from .models import TickData, BarData, Period
from .utils import check_redis, parse_symbol, redis_client, lifespan

# 创建FastAPI应用
app = FastAPI(**API_CONFIG, lifespan=lifespan)

@app.get("/tick/{symbol}")
async def get_tick_data(symbol: str, start_time: Optional[int] = None, end_time: Optional[int] = None):
    """获取Tick数据
    
    Args:
        symbol: 合约代码(格式: SHFE:au2306)
        start_time: 开始时间戳(可选)
        end_time: 结束时间戳(可选)
    
    Returns:
        List[TickData]: Tick数据列表
    """
    check_redis()
    try:
        exchg, code = parse_symbol(symbol)
        key = f"tick:{exchg}:{code}"
        
        # 构建时间范围条件
        if start_time is None and end_time is None:
            data = redis_client.zrange(key, 0, -1, withscores=True)
        else:
            min_score = "-inf" if start_time is None else start_time
            max_score = "+inf" if end_time is None else end_time
            data = redis_client.zrangebyscore(key, min_score, max_score, withscores=True)
        
        # 解析数据
        result = []
        for item, score in data:
            tick_data = json.loads(item)
            result.append(TickData(**tick_data))
        
        logger.info(f"Retrieved {len(result)} tick records for {symbol}")
        return result
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error fetching tick data for {symbol}: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/bar/{symbol}/{period}")
async def get_bar_data(
    symbol: str, 
    period: Period,
    start_time: Optional[int] = None,
    end_time: Optional[int] = None
):
    """获取K线数据
    
    Args:
        symbol: 合约代码(格式: SHFE:au2306)
        period: K线周期
        start_time: 开始时间戳(可选)
        end_time: 结束时间戳(可选)
    
    Returns:
        List[BarData]: K线数据列表
    """
    check_redis()
    try:
        exchg, code = parse_symbol(symbol)
        key = f"bar:{exchg}:{code}:{period}"
        
        # 构建时间范围条件
        if start_time is None and end_time is None:
            data = redis_client.zrange(key, 0, -1, withscores=True)
        else:
            min_score = "-inf" if start_time is None else start_time
            max_score = "+inf" if end_time is None else end_time
            data = redis_client.zrangebyscore(key, min_score, max_score, withscores=True)
        
        # 解析数据
        result = []
        for item, score in data:
            bar_data = json.loads(item)
            result.append(BarData(**bar_data))
        
        logger.info(f"Retrieved {len(result)} bar records for {symbol} period {period}")
        return result
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error fetching bar data for {symbol}: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/symbols")
async def get_symbols():
    """获取所有可用的合约列表"""
    check_redis()
    try:
        # 从Redis获取所有tick key
        keys = redis_client.keys("tick:*")
        symbols = []
        for key in keys:
            _, exchg, code = key.split(":")
            symbols.append(f"{exchg}:{code}")
        return symbols
    except Exception as e:
        logger.error(f"Error fetching symbols: {e}")
        raise HTTPException(status_code=500, detail=str(e)) 